package com.jhx.video.videomanager

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import cn.jzvd.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Video
import com.jhx.common.utils.ImageLoader
import com.jhx.common.utils.UserManager
import com.jhx.video.R
import com.jhx.video.widget.VideoManagerDialog
import kotlinx.android.synthetic.main.fragment_store_manager.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 店铺管理页面
 *
 * @author Jack 2018-03-07 19:40
 */
class VideoManagerFragment : QuickBaseFragment(), Contract.StoreManagerView {
    private var mAdapater: BaseQuickAdapter<Video, BaseViewHolder>? = null
    private var mPresenter: VideoManagerPresenterImpl? = null
    private var mDialog: VideoManagerDialog? = null
    private var mEmptyView: View? = null
    private var mVideo: Video? = null
    private var mPositon: Int = 0
    private var mPageIndex = 1
    private var mPageSize = 10

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_store_manager, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mEmptyView = view?.findViewById(R.id.empty_layout)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mPresenter = VideoManagerPresenterImpl()
        mPresenter?.setView(this)
        mPresenter?.getVideoList(mPageIndex, mPageSize,{
            showLoadingDialog()
        }) {
            hideLoadingDialog()
        }
        mAdapater = object: BaseQuickAdapter<Video, BaseViewHolder>(R.layout.item_video_manager) {
            @SuppressLint("SimpleDateFormat")
            override fun convert(holder: BaseViewHolder?, video: Video?) {
                val moreImage = holder?.getView<ImageView>(R.id.img_more)
                val shareText = holder?.getView<TextView>(R.id.txt_share)
                val messageText = holder?.getView<TextView>(R.id.txt_message)
                val browseText = holder?.getView<TextView>(R.id.txt_number)
                val favourText = holder?.getView<TextView>(R.id.txt_favour)
                val videoview = holder?.getView<View>(R.id.videoview) as JZVideoPlayerStandard
                holder.getView<TextView>(R.id.txt_desc)?.text = "${video?.context}"
                shareText?.text = if(!TextUtils.isEmpty(video?.share_video_num) && video?.share_video_num!!.toInt() >= 10000) {
                    "${video.share_video_num!!.toInt()/10000 }.${video.share_video_num!!.toInt()%10000/1000}w"
                } else {
                    video?.share_video_num
                }
                messageText?.text = if(!TextUtils.isEmpty(video?.comment_num) && video?.comment_num!!.toInt() >= 10000) {
                    "${video.comment_num!!.toInt()/10000 }.${video.comment_num!!.toInt()%10000/1000}w"
                } else {
                    video?.comment_num
                }
                browseText?.text = if(!TextUtils.isEmpty(video?.play_num) && video?.play_num!!.toInt() >= 10000) {
                    "${video.play_num!!.toInt()/10000 }.${video.play_num!!.toInt()%10000/1000}w"
                } else {
                    video?.play_num
                }
                favourText?.text = if(!TextUtils.isEmpty(video?.praise_num) && video?.praise_num!!.toInt() >= 10000) {
                    "${video.praise_num!!.toInt()/10000 }.${video.praise_num!!.toInt()%10000/1000}w"
                } else {
                    video?.praise_num
                }
                if(video?.is_top == 1) {
                    holder.getView<ImageView>(R.id.img_top).visibility = View.VISIBLE
                } else {
                    holder.getView<ImageView>(R.id.img_top).visibility = View.GONE
                }
                videoview.setUp("${video?.video_url}", JZVideoPlayer.SCREEN_WINDOW_LIST)
                ImageLoader.get().loadImageByUrl(activity, UserManager.get().user.headImage, holder?.getView(R.id.img_head))
                ImageLoader.get().loadImageByUrl(activity, video?.cover_url, videoview?.thumbImageView)
                holder.setText(R.id.txt_name, UserManager.get().user.businessName)
                moreImage?.setOnClickListener {
                    mPositon = holder.adapterPosition
                    if(mDialog == null) {
                        mDialog = VideoManagerDialog(activity)
                    }
                    if(video?.is_top == Video.STATUS_ISTOP) {
                        mDialog?.setTopText("取消置顶")
                    } else {
                        mDialog?.setTopText("置顶")
                    }
                    mDialog?.onItemClick = { _, index ->
                        when(index) {
                            0 -> {
                                if(video?.is_top == Video.STATUS_ISTOP) {
                                    mPresenter?.stickVideo("${video.id}", Video.STATUS_NOTTOP)
                                } else {
                                    mPresenter?.stickVideo("${video?.id}", Video.STATUS_ISTOP)
                                }
                            }
                            1 -> {
                                mVideo = video
                                mPresenter?.deleteVideo("${video?.id}")
                            }
                        }
                    }
                    mDialog?.show()
                }
                if(video?.create_time != null) {
                    val date = Date(video.create_time!!)
                    val time = SimpleDateFormat("MM-dd").format(date)
                    holder.setText(R.id.txt_time, time)
                }
            }

        }
        mAdapater?.setOnLoadMoreListener({
            mPresenter?.getVideoList(mPageIndex, mPageSize, {}, {})
        }, recycler_view)
        recycler_view.itemAnimator = DefaultItemAnimator()
        recycler_view.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = mAdapater
        refresh_layout.setOnRefreshListener {
            mPageIndex = 1
            refresh_layout.isRefreshing = true
            mPresenter?.getVideoList(mPageIndex, mPageSize, {}, {})
        }
        recycler_view.addOnChildAttachStateChangeListener(object: RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewDetachedFromWindow(view: View?) {
                val jzvd = view?.findViewById<JZVideoPlayerStandard>(R.id.videoview)
                if (jzvd != null && JZUtils.dataSourceObjectsContainsUri(jzvd.dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
                    if (JZVideoPlayerManager.getCurrentJzvd() != null &&
                            JZVideoPlayerManager.getCurrentJzvd().currentScreen != JZVideoPlayer.SCREEN_WINDOW_FULLSCREEN) {
                        JZVideoPlayer.releaseAllVideos()
                    }
                }
            }

            override fun onChildViewAttachedToWindow(view: View?) {

            }

        })
    }

    override fun getListSuccess(videoList: List<Video>?) {
        if(videoList?.isNotEmpty() == true) {
            mEmptyView?.visibility = View.GONE
            recycler_view.visibility = View.VISIBLE
            if(mPageIndex == 1) {
                mAdapater?.data?.clear()
                mAdapater?.setNewData(videoList)
                refresh_layout.isRefreshing = false
            } else {
                mAdapater?.addData(videoList)
                mAdapater?.loadMoreComplete()
            }
            mPageIndex ++
        } else {
            refresh_layout.isRefreshing = false
            if(mPageIndex > 1) {
                mAdapater?.loadMoreEnd()
            } else {
                mEmptyView?.visibility = View.VISIBLE
                recycler_view.visibility = View.GONE
            }
        }
    }

    override fun deleteVideoSuccess() {
        if(mVideo != null) {
            mAdapater?.data?.remove(mVideo)
        }
        mAdapater?.notifyDataSetChanged()
    }

    override fun stickVideoSuccess() {
        val video = mAdapater?.data?.get(mPositon)
        if(video?.is_top == Video.STATUS_ISTOP) {
            video.is_top = Video.STATUS_NOTTOP
        } else {
            video?.is_top = Video.STATUS_ISTOP
        }
        mPageIndex = 1
        mPresenter?.getVideoList(mPageIndex, mPageSize, onStart = {
            showLoadingDialog()
        }) {
            hideLoadingDialog()
        }
    }

    override fun getListError() {

    }

    override fun getContext(): Activity {
        return activity
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    @SuppressLint("MissingSuperCall")
    override fun onPause() {
        super.onPause()
        JZVideoPlayer.releaseAllVideos()
    }
}